<?php

namespace app\admin\controller\setting;

use app\common\controller\AdminController;
use think\facade\Cache;

/**
 * 酒店
 */
class Store extends AdminController
{
    
    /**
     * CrsHotel模型对象
     */
    protected $model = null;

    public function __construct() {
            parent::__construct();
            $this->model = model('CrsHotel');
            $this->view->assign("statusList", $this->model->getStatusList());
            $this->view->assign("provinceList", $this->model->getProvinceList());
            $this->view->assign("firstCityList", $this->model->getFirstCityList());
        }
    
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->get('type') == 'ajax') {
            $page = $this->request->get('page', 1);
            $limit = $this->request->get('limit', 10);
            $search = (array)$this->request->get('search', []);
            return json($this->model->getCrsHotelList($page, $limit, $search));
        }
        $basic_data = [
            'title' => '酒店',
            'data'  => '',
        ];
        return $this->fetch('', $basic_data);
    }

    /**
     * 添加
     * @return mixed
     */
    public function add() {
        if (!$this->request->isPost()) {
            $basic_data = [
                'title' => '添加酒店',
            ];
            return $this->fetch('add', $basic_data);
        } else {
            $post = $this->request->post();

            //验证数据
            $validate = $this->validate($post, 'app\admin\validate\CrsHotel.add');
            if (true !== $validate) return __error($validate);
            $info = $this->model->where('name',$post['name'])->find();
            if($info) return __error('酒店名称重复');

            //保存数据,返回结果
            $post['create_time'] = strtotime($post['create_time']);
            return $this->model->add($post);
        }
    }

    /**
     * 修改
     * @return mixed|string|\think\response\Json
     */
    public function edit() {
        $empMd = model('PmsEmployee');
        if (!$this->request->isPost()) {
            $hotel_id = $this->request->get('id');
            //查找所需修改的酒店
            $data = $this->model->where('id', $hotel_id)->find();
            if (empty($data)) return msg_error('暂无数据，请重新刷新页面！');
            $city = $this->model->getCityList($data['province']);
            $employee = $empMd->getHotelEmp($hotel_id);
            //基础数据
            $basic_data = [
                'title'    => '修改酒店',
                'info' => $data,
                'cityList' => $city,
                'employeeList' => $employee,
            ];
            return $this->fetch('edit', $basic_data);
        } else {
            $post = $this->request->post();

            //验证数据
            $validate = $this->validate($post, 'app\admin\validate\CrsHotel.edit');
            if (true !== $validate) return __error($validate);
            // if(!empty($post['is_boss'])){
            //     $bosses = $empMd->where('id',$post['is_boss'])->value('is_boss');
            //     if(empty($bosses)){
            //         $empMd->where('id',$post['is_boss'])->setField('is_boss',$post['id']);
            //     }else{
            //         $bosses .= ','.$post['id'];
            //         $empMd->where('id',$post['is_boss'])->setField('is_boss',$bosses);
            //     }
            // }
            if(!empty($post['is_boss'])){
                $empMd->where('id',$post['is_boss'])->setField('is_boss',1);
            }else{
                $empMd->where('id',$post['is_boss'])->setField('is_boss',0);
            }
            unset($post['is_boss']);

            //保存数据,返回结果
            $post['create_time'] = strtotime($post['create_time']);
            return $this->model->edit($post);
        }
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function del() {
        $get = $this->request->get();

        //验证数据
        if (!is_array($get['id'])) {
            $validate = $this->validate($get, 'app\admin\validate\CrsHotel.del');
            if (true !== $validate) return __error($validate);
        }

        //执行删除操作
        return $this->model->del($get['id']);
    }

    /**
     * 更改状态
     * @return \think\response\Json
     */
    public function status() {
        $get = $this->request->get();

        //验证数据
        $validate = $this->validate($get, 'app\admin\validate\CrsHotel.status');
        if (true !== $validate) return __error($validate);

        //判断状态
        $status = $this->model->where('id', $get['id'])->value('status');
        $status == 1 ? list($msg, $status) = ['启用成功', $status = 0] : list($msg, $status) = ['禁用成功', $status = 1];

        //执行更新操作操作
        $update = $this->model->where('id', $get['id'])->update(['status' => $status]);

        if ($update >= 1) return __success($msg);
        return __error('数据有误，请刷新重试！');
    }

    public function getCity(){
        $province = $this->request->get('province');
        return $this->model->getCityList($province);
    }

    public function export(){
        $page = $this->request->get('page', 1);
        $flag = $this->request->get('flag');
        $limit = 100;
        $search = (array)$this->request->get('search', []);
        $allData = $this->model->getCrsHotelList($page, $limit, $search);
        $data = $allData['data']->toArray();

        if($page == 1){
            if($allData['count'] > 0){
                Cache::set('exp_store_xls_'.$flag,['count'=>$allData['count'],'data'=>[]],60);
            }else{
                return __error('没有符合条件的数据!');
            }
        }
        if($data){
            $cacheinfo=Cache::get('exp_store_xls_'.$flag);
            $allpage=ceil( $cacheinfo['count'] / $limit );
            $newlist=array_merge($cacheinfo['data'],$data);
            Cache::set('exp_store_xls_'.$flag,['count'=>$cacheinfo['count'],'data'=>$newlist],60);
            return json(['code'=>0,'msg'=>'正在导出……进度为（'.$page.'/'.$allpage.'）','allpage'=>$allpage,'page'=>$page+1]);
        }else{
            $xlsName = "集团门店信息";
            $xlsCell = [
                ['id','酒店ID'],
                ['hotel_num','酒店编号'],
                ['name','酒店名称'],
                ['province_text','省份'],
                ['city_text','城市'],
                ['address','详细地址'],
                ['contacts','联系人'],
                ['contact_tel','联系电话'],
                ['new_create_time','创建时间'],
                ['is_boss','绑定Boss'],
                ['status_text','是否开业'],
                ['commission','佣金比'],
            ];
            $cacheinfo=Cache::get('exp_store_xls_'.$flag);
            exportExcel($xlsName, $xlsCell, $cacheinfo['data']);
        }
        // $field = 'id,hotel_num,name,province,city,address,contacts,contact_tel,create_time,status,commission';
        // $data = $this->model->where('status','>=','0')->field($field)->order(['id' => 'desc'])->select()->toArray();
        // foreach($data as $k => $v){
        //     $data[$k]['province'] = $v['province'] > 0 ? db('system_area')->where('id',$v['province'])->value('shortname') : '——';
        //     $data[$k]['city'] = $v['city'] > 0 ? db('system_area')->where('id',$v['city'])->value('shortname') : '——';
        //     $is_boss = model('PmsEmployee')->where(['status'=>1,'is_boss'=>1])->where('FIND_IN_SET('.$v['id'].',hotel_ids)')->value('name');
        //     $data[$k]['is_boss'] = $is_boss ? $is_boss : '暂无';
        // }
        // $cellName = [
        //     ['id','酒店ID'],
        //     ['hotel_num','酒店编号'],
        //     ['name','酒店名称'],
        //     ['province','省份'],
        //     ['city','城市'],
        //     ['address','详细地址'],
        //     ['contacts','联系人'],
        //     ['contact_tel','联系电话'],
        //     ['create_time_text','创建时间'],
        //     ['status_text','是否开业'],
        //     ['commission','佣金比'],
        // ];
        // exportExcel('集团门店信息',$cellName,$data);
    }
}
